package com.sunmi.usercenter.bean.rpc;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.sunmi.usercenter.Constant;
import com.sunmi.usercenter.utils.DateUtils;
import com.sunmi.usercenter.utils.DesUtils;
import com.sunmi.usercenter.utils.MD5Utils;

/**
 * 请求加密实体
 * 
 * @author longtao.li
 */
public class MD5Req<T> {

	public MD5Req(T params) {
		this.params = params;
		md5();
	}

	public MD5Req(T params, String isEncrypted) {
		this.params = params;
		this.isEncrypted = isEncrypted;
		md5();
	}

	public T params;								 	// 请求携带的数据
	public String jsonParams = ""; 						// params的json字符串
	public String isEncrypted = Constant.isEncrypted;   // 是否加密
	public String timeStamp = ""; 						// 时间戳
	public String randomNum = ""; 						// 随机数(6位)
	public String sign = ""; 							// md5加密后的字符串

	// 计算方法：
	// MD5(Parameter + IsEncrypted + TimeStamp + RandomNum + MD5(Key))
	private void md5() {
		if (TextUtils.isEmpty(timeStamp)) {
			timeStamp = DateUtils._getGMTime() + "";
		}
		while (randomNum.length() < 6)
			randomNum += (int) (Math.random() * 10);

		jsonParams = new Gson().toJson(params);
		jsonParams = jsonParams.replace(" ", "");

		if (isEncrypted.equals("1")) {
			try {
				jsonParams = DesUtils.encode(Constant.DES_KEY, jsonParams);
				// System.out.println("jsonParams:" + jsonParams);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		sign = jsonParams + isEncrypted + timeStamp + randomNum
				+ MD5Utils.md5(Constant.IDELIVER_KEY);
		sign = MD5Utils.md5(sign);
	}

}
